import os
import re
import tarfile
import json
import psutil
import time
import datetime
import requests
import api.analyze
from api.ip import ipAnalysis
import socket
from lib.data import config, classtype,running_status
from flask import redirect, url_for

def map(begintime=None, endtime=None):
    result = api.analyze.analyze_suricata_alert(
        data="xy", language="zh-CN", begintime=begintime, endtime=endtime)
    return result


def ip(begintime=None, endtime=None):
    ipResult = api.analyze.analyze_suricata_alert(
        data="ip", begintime=begintime, endtime=endtime)
    return ipResult

def make_tar():
    try:
        os.remove("{}/ThirPath/suricata/marioips/marioips.tar.gz".format(os.getcwd))
    except:
        pass
    with tarfile.open("./ThirPath/suricata/marioips.tar.gz", "w:gz") as tar:
        tar.add("./ThirPath/suricata/marioips/",
                arcname=os.path.basename("./ThirPath/suricata/marioips/"))

def get_allrules(server, query=" "):
    allrules = []
    if server == "client":
        originalrules_file = open(
            './ThirPath/suricata/marioips/rules/local.rules', 'r')
    else:
        originalrules_file = open(
            './ThirPath/suricata/marioips/rules/all.rules', 'r')
    originalrules = originalrules_file.readlines()
    for originalrule in originalrules:
        rule_info = {}
        rule_info['msg'] = re.findall(
                r'"(.*?)"', originalrule, re.S)[0]
        rule_info['sid'] = re.findall(
                r'sid:(.*?);', originalrule, re.S)[0].strip()
        if query == rule_info['sid'] or query.lower() in rule_info['msg'].lower():
            if server == "client":
                rule_info['type'] = re.findall(
                    r'^(.*?) ', originalrule, re.S)[0]
            rule_info['content_type'] = re.findall(
                r' (.*?) ', originalrule, re.S)[0].upper()
            try:
                rule_info['class_type'] = classtype[re.findall(
                    r'classtype:(.*?);', originalrule, re.S)[0]]
            except:
                rule_info['class_type'] = re.findall(
                    r'classtype:(.*?);', originalrule, re.S)[0]
            allrules.append(rule_info)
    originalrules_file.close()
    return allrules


def set_clientrules(rules_info):
    with open('./ThirPath/suricata/marioips/rules/local.rules','r') as now_rules:
        rules = now_rules.readlines()
        rules_id = []
        for rule in rules:
            sid = re.findall(r'sid:(.*?);', rule, re.S)[0].strip()
            rules_id.append(sid)
    originalrules_file = open(
        './ThirPath/suricata/marioips/rules/all.rules', 'r')
    originalrules = originalrules_file.readlines()
    clientrules_file = open(
        './ThirPath/suricata/marioips/rules/local.rules', 'a+')
    for info in rules_info:
        for rule in originalrules:
            sid = re.findall(
                    r'sid:(.*?);', rule, re.S)[0].strip()
            if info['id'] == sid not in rules_id:
                print(sid)
                clientrules_file.write(rule.replace(
                    re.search(r'^(.*?) ', rule, re.S).group(0), info['type'] + " "))
    clientrules_file.close()
    originalrules_file.close()
    return "yes"

def del_rules(del_sid):
    reman_rules = []
    if del_sid == "all":
        with open('./ThirPath/suricata/marioips/rules/local.rules', 'w') as f:
            f.truncate()
        return "del all rules ok"
    del_result="del false"
    with open('./ThirPath/suricata/marioips/rules/local.rules', 'r') as clientrules_file:
        for rules in clientrules_file:
            sid = re.findall(
                    r'sid:(.*?);', rules, re.S)[0].strip()
            if sid != del_sid:
                reman_rules.append(rules)
            else:
                del_result="del rules {} ok".format(del_sid)
    with open('./ThirPath/suricata/marioips/rules/local.rules', 'w') as f:
        for rules in reman_rules:
            f.write(rules)
    return del_result


def change_rules(change_sid,chang_type):
    reman_rules = []
    del_result="del false"
    with open('./ThirPath/suricata/marioips/rules/local.rules', 'r') as clientrules_file:
        for rules in clientrules_file:
            sid = re.findall(
                    r'sid:(.*?);', rules, re.S)[0].strip()
            if sid != change_sid:
                reman_rules.append(rules)
            else:
                rules_type = re.findall(
                    r'^(.*?) ', rules, re.S)[0]
                rules = rules.replace(rules_type,chang_type)
                reman_rules.append(rules)
    with open('./ThirPath/suricata/marioips/rules/local.rules', 'w') as f:
        for rules in reman_rules:
            f.write(rules)
    return del_result

def customization_install(src_ip):
    netcard_info = []
    config['ip'] = ipAnalysis.get_local_ip()
    info = psutil.net_if_addrs()
    for k, v in info.items():
        for item in v:
            if item[0] == 2 and not item[1] == '127.0.0.1':
                netcard_info.append(item[1])
    src_ip = re.findall(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', src_ip, re.S)[0]
    for ip in netcard_info:
        if src_ip in ip:
            install_ip = ip
        else:
            continue
    try:
        install_file = open(os.getcwd() + "/ThirPath/suricata/install.sh", "r")
        file_read = install_file.read().replace("ipadd", install_ip)
        install_file.close()
        return file_read
    except:
        install_file = open(os.getcwd() + "/ThirPath/suricata/install.sh", "r")
        file_read = install_file.read().replace("ipadd", config['ip'][0])
        install_file.close()
        return file_read


def search_venuseye(ip):
    result = {}
    result['vendor'] = 'venuseye'
    try:
        search_result = json.loads(requests.post(
            "https://www.venuseye.com.cn/ve/ip", {'target': '{}'.format(ip)}).text)
    except:
        search_result = None
    if search_result != None:
        result['original'] = search_result
        try:
            result['threat_score'] = search_result['data']['threat_score']
        except:
            result['threat_score'] = 'None'
        try:
            result['active_time'] = search_result['data']['active_time']
        except:
            result['active_time'] = 'None'
    return result


def search_virustotal(ip):
    result = {}
    result['vendor'] = 'virustotal'
    headers = {
        "x-apikey": "e6184c04de532cd5a094f3fd6b3ce36cd187e41e671b5336fd69862257d07a9a",
    }
    url = 'https://www.virustotal.com/api/v3/ip_addresses/{}'.format(ip)
    resp = requests.get(url, headers=headers)
    search_result = json.loads(resp.text)
    try:
        search_result = json.loads(requests.get(url, headers=headers).text)
    except:
        search_result = None
    if search_result != None:
        result['original'] = search_result
        analysis_results = search_result['data']['attributes']['last_analysis_stats']
        threat_score = analysis_results['malicious']+analysis_results['suspicious']
        if threat_score == 0:
            result['threat_score'] = "None"
        else:
            result['threat_score'] = threat_score

    return result


def vul_search(ip):
    search_result = []
    search_result.append(search_virustotal(ip))
    search_result.append(search_venuseye(ip))
    return search_result

def get_status():
    start_time = running_status['starttime']
    now_time = datetime.datetime.now()
    time_diff = now_time-start_time
    timestatus={}
    diss_seconds = time_diff.seconds
    timestatus['minutes'],timestatus['secouds'] = divmod(diss_seconds,60)
    timestatus['hours'],timestatus['minutes'] = divmod(timestatus['minutes'],60)
    timestatus['days'],timestatus['hours'] = divmod(timestatus['hours'],24)
    return json.dumps(timestatus)